package com.BMS.DAOImpl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.BMS.DAO.ViolationDao;
import com.BMS.entity.Book;
import com.BMS.entity.Violation;

/**
 * 违规记录实体类DAO层接口实现类
 * @author lenovo
 *
 */
@Repository("ViolationDaoImpl")
public class ViolationDaoImpl implements ViolationDao {

	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public void addViolation(Violation violation) {
		String sql = "SELECT violate(?,?,?,?,?)";
		SQLQuery q = this.getSession().createSQLQuery(sql);
		q.setString(0, violation.getType());
		q.setString(1, violation.getReader_ID());
		q.setString(2, violation.getManager_ID());
		q.setString(3, violation.getBook_ID());
		q.setDate(4, violation.getReg_date());
		List list = q.list();
	}

	@Override
	public void deleteViolationById(int violation_id) {
		this.getSession().createQuery("delete Violation where violation_ID=?").setParameter(0, violation_id).executeUpdate();
	}

	@Override
	public Violation findViolationById(int violation_id) {
		return (Violation)this.getSession().createQuery("from Violation where violation_ID=?").setParameter(0, violation_id).uniqueResult();
	}

	@Override
	public List<Violation> findViolationsByReaderId(String reader_id) {
		return (List<Violation>)this.getSession().createQuery("from Violation where reader_ID=?").setParameter(0, reader_id).list();
	}
	
	// 分页查询图书，并按指定字段排序
	public List<Violation> findAllViolations(int offset, int length, String orderBy) {
		
		List<Violation> violationList = null;
		Session session = this.getSession();
		Query query = session.createQuery("from Violation v order by ? desc").setParameter(0, "v."+orderBy);
		query.setFirstResult(offset);
		query.setMaxResults(length);
		violationList = query.list();
		//System.out.println(orderBy);
		return violationList;
		
	}

	// 显示分页总页数
	public long getPageCount() {
		Query query = this.getSession().createQuery("SELECT COUNT(*) FROM Violation");
		// 每页10行记录
		return (long)Math.ceil(Double.parseDouble(query.uniqueResult().toString())/10);
	}

	@Override
	public void updateViolation(Violation violation) {
		this.getSession().update(violation);
	}

}
